package com.songshuai.sales.tool.service.impl;

import com.songshuai.sales.tool.dao.tool.SopTypeMapper;
import com.songshuai.sales.tool.dto.request.soptype.SopTypeReqDto;
import com.songshuai.sales.tool.dto.response.login.LoginUserResDto;
import com.songshuai.sales.tool.dto.response.soptype.SopTypeDto;
import com.songshuai.sales.tool.model.SopType;
import com.songshuai.sales.tool.service.SopService;
import com.songshuai.sales.tool.service.SopTypeService;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SopTypeServiceImpl extends BaseServiceImpl implements SopTypeService {

    @Autowired
    private SnowFlakeUtil snowFlakeUtil;

    @Autowired
    private SopTypeMapper sopTypeMapper;

    @Autowired
    private SopService sopService;

    @Override
    @Transactional
    public void updateShowStatus(Integer isShow, String id) {
        LoginUserResDto loginUser = getCurrentUser();
        Map map = new HashMap();
        map.put("isShow", isShow);
        map.put("parentId", id);
        map.put("updateBy", loginUser.getUserId());
        sopTypeMapper.updateShowStatus(map);
    }

    /**
     * 基础服务使用
     * 查询一级/二级分类集合
     *
     * @return
     */
    public List<SopTypeDto> querySopTypeList(BaseParmDto<String> param) {
        List<SopTypeDto> sopTypeList = sopTypeMapper.querySopTypeList(param);
        if(!CollectionUtils.isEmpty(sopTypeList)){
            for(int i = 0; i < sopTypeList.size(); i++){
                SopTypeDto sopType = sopTypeList.get(i);
                Integer num = sopType.getNum();
                // 判断同级分类中是不是最后一个分类
                if(i == sopTypeList.size() - 1){
                    sopType.setLast(true);
                }else{
                    sopType.setLast(false);
                }
                if(i == 0){
                    sopType.setFirst(true);
                }else{
                    sopType.setFirst(false);
                }
            }
        }
        return sopTypeList;
    }

    @Override
    @Transactional
    public Integer sopTypeSort(String typeId, String orderBy) {
        Integer flag = 0;
        Date date = new Date();
        LoginUserResDto loginUser = getCurrentUser();
        SopType sopType = sopTypeMapper.selectByPrimaryKey(typeId);
        if(null != sopType){
            Integer typeSort = sopType.getTypeSort();
            Map map = new HashMap();
            map.put("parentId", sopType.getParentId());
            map.put("typeSort", sopType.getTypeSort());
            map.put("operator", orderBy);
            SopType sortType = sopTypeMapper.sopTypeSort(map);
            if(null != sortType){
                // 更新分类顺序 orderBy:asc上升 desc下降)
                sopType.setTypeSort(sortType.getTypeSort());
                sopType.setUpdateTime(date);
                sopType.setUpdateBy(loginUser.getUserId());
                sopTypeMapper.updateByPrimaryKey(sopType);
                sortType.setTypeSort(typeSort);
                sortType.setUpdateTime(date);
                sortType.setUpdateBy(loginUser.getUserId());
                sopTypeMapper.updateByPrimaryKey(sortType);
            }else{
                flag = 2;
            }
        }else{
            flag = 1;
        }
        return flag;
    }

    @Override
    @Transactional
    public Integer saveOrUpdateSopType(SopTypeReqDto sopType) {
        Integer flag = 0;
        Date date = new Date();
        LoginUserResDto loginUser = getCurrentUser();
        if(StringUtils.hasText(sopType.getId())){
            String id = sopType.getId();
            String parentId = sopType.getParentId();
            Map map = new HashMap();
            map.put("parentId", parentId);
            map.put("typeId", id);
            map.put("typeName", sopType.getTypeName());
            Integer num = sopTypeMapper.querySopTypeNumByName(map);
            if(num > 0){
                flag = 1;
                return flag;
            }
            SopType oldSopType = sopTypeMapper.selectByPrimaryKey(id);
            if(null == oldSopType){
                flag = 2;
                return flag;
            }
            SopType type = new SopType();
            BeanUtils.copyProperties(sopType, type);
            // 更新下级分类显示状态
            if(oldSopType.getIsShow() != sopType.getIsShow()){
                if(sopType.getIsShow() == 0){
                    updateShowStatus(sopType.getIsShow(), id);
                }
            }
            sopTypeMapper.updateByPrimaryKey(type);
            // 更新关联的sop内容
            if(!oldSopType.getParentId().equals(sopType.getParentId())){
                sopService.updateSopMainType(parentId, id);
            }

        } else {
            if(StringUtils.isEmpty(sopType.getTypeName())){
                flag = 1;
                return flag;
            }
            Map map = new HashMap();
            map.put("parentId", sopType.getParentId());
            map.put("typeId", sopType.getId());
            map.put("typeName", sopType.getTypeName()); 
            Integer num = sopTypeMapper.querySopTypeNumByName(map);
            if(num > 0){
                flag = 2;
                return flag;
            }
            String id = snowFlakeUtil.nextId();
            String parentId = sopType.getParentId();
            if(StringUtils.isEmpty(sopType.getParentId())){
                parentId = "0";
            }
            // 查询同级分类最大排序值
            Integer maxSort = sopTypeMapper.queryMaxSort(parentId);
            SopType type = new SopType();
            BeanUtils.copyProperties(sopType, type);
            type.setId(id);
            type.setCreateTime(date);
            type.setCreateBy(loginUser.getUserId());
            type.setTypeSort(maxSort + 1);
            sopTypeMapper.insertSelective(type);
        }
        return flag;
    }

    @Override
    @Transactional
    public Integer deleteSopTypeById(String id) {
        Integer flag = 0;
        SopType sopType = sopTypeMapper.selectByPrimaryKey(id);
        if(null == sopType){
            flag = 3;
        }
        LoginUserResDto loginUser = getCurrentUser();
        Integer num = querySubTypeById(id);
        Integer count = sopService.querySopCountByTypeId(id);
        // 删除分类时，如该分类无下级分类，则查询是否有内容与该分类关联，如有内容关联，则提示请先删除关联内容。
        if(num == 0 && count == 0){
            Map map = new HashMap();
            map.put("isDelete", 1);
            map.put("updateBy", loginUser.getUserId());
            map.put("id", id);
            sopTypeMapper.updateDeleteStatus(map);
        }else if(num > 0){
            flag = 1;
        }else if(count > 0){
            flag = 2;
        }
        return flag;
    }

    @Override
    public Integer querySubTypeById(String typeId) {
        Integer count = 0;
        BaseParmDto param = new BaseParmDto();
        param.setParam(typeId);
        List<SopTypeDto> sopTypeList = sopTypeMapper.querySopTypeList(param);
        if(!CollectionUtils.isEmpty(sopTypeList)){
            count = sopTypeList.size();
        }
        return count;
    }

    @Override
    public SopTypeDto getSopTypeDetailByTypeId(String typeId) {
        SopType sopType = sopTypeMapper.selectByPrimaryKey(typeId);
        if(null != sopType){
            SopTypeDto sopTypeDto = new SopTypeDto();
            BeanUtils.copyProperties(sopType, sopTypeDto);
            return sopTypeDto;
        }
        return null;
    }
}
